package com.northpool.operator.cicd.ssh;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(
        ref = "SshFileRenameOperator",
        name = "sftp文件移动",
        description = "sftp文件移动、重命名",
        version = "1.0.0"
)
@OutputParams({
        @OutputParam(ref = "newPath", name = "新文件路径", desc = "新文件路径")
})
public class SshFileRenameOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "host", name = "主机", desc = "主机IP或域名，如：10.80.9.11", required = true),
            @InputParam(ref = "port", name = "端口", desc = "SSH服务端口，如：22", value = "22", type = TypeEnum.NUMBER),
            @InputParam(ref = "user", name = "用户名", desc = "登录用户名，如：test", required = true),
            @InputParam(ref = "pass", name = "密码", desc = "登录密码，如：password", required = true, type = TypeEnum.SECRET),
            @InputParam(ref = "oldPath", name = "旧文件路径", desc = "旧文件路径，如：/data/temp/test.txt", required = true),
            @InputParam(ref = "newPath", name = "新文件路径", desc = "新文件路径，如：/data/temp/test_new.txt", required = true)
    })
    public SshFileRenameOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(SshFileRenameOperator.class, TestParamBuilder.aBuilder()
                .param("host", "192.168.5.11")
                .param("port", "22")
                .param("user", "root")
                .param("pass", "950519")
                .param("oldPath", "/root/stp-jianmu_new.zip")
                .param("newPath", "/root/tmp/stp-jianmu_new.zip")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String host = paramTool.getStr("host");
        int port = paramTool.getNumber("port").intValue();
        String user = paramTool.getStr("user");
        String pass = paramTool.getStr("pass");
        String oldPath = paramTool.getStr("oldPath");
        String newPath = paramTool.getStr("newPath");

        JschUtils jschUtils = new JschUtils();
        try {
            jschUtils.connect(user, pass, host, port);
            jschUtils.rename(oldPath, newPath);
            this.log("移动文件完成");
            this.result("newPath", newPath);
        } catch (Exception e) {
            String stacktrace = ExceptionUtil.stacktraceToString(e);
            this.error("重命名远程文件失败，错误堆栈: {}", stacktrace);
        } finally {
            jschUtils.close();
        }

    }
}
